package com.mulanweb.api.module.controller.wechat;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.mulanweb.api.module.controller.BaseController;
import com.mulanweb.api.module.model.*;
import com.mulanweb.db.common.Constant;
import com.mulanweb.db.common.SQLGenerateHelper;
import com.mulanweb.handler.CouponHandler;
import com.mulanweb.handler.wechat.UserHandler;
import com.mulanweb.utils.DateUtil;
import com.mulanweb.utils.RandomUtil;
import com.mulanweb.validator.annotation.ValidateFile;
import com.mulanweb.validator.annotation.ValidateForm;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/11/8 0008.
 */
@ValidateFile
public class OrderController extends BaseController {

    @ValidateForm
    public synchronized void save() {

        String openId = super.getSessionAttr("openId");
        // String openId = "oULNBwOvt_D2A_8se1bQOQ06ky0w";
        Map<String, Object> result = new HashMap<String, Object>();

        if(super.getSessionAttr("tokenTime") !=null){
            Date tokenTime =super.getSessionAttr("tokenTime");
            Long tokenTimeMsec = tokenTime.getTime();
            Long currentTimeMsec = new Date().getTime();
            if((currentTimeMsec - tokenTimeMsec) < 500){
                returnJson(0, "操作过于频繁");
                super.setSessionAttr("tokenTime",new Date());
                return;
            }else{
                super.setSessionAttr("tokenTime",new Date());
            }
        }else{
            super.setSessionAttr("tokenTime",new Date());
        }

        User user = User.dao.findFirst("SELECT * FROM user where open_id = ?", openId);

        Long userId = null;
        if (UserHandler.userNotNull(openId)) {
            userId = user.getId();
        } else {
            returnJson(0, Constant.PromptMessage.NOT_EXIST_USER);
            return;
        }

        List<Order> userList = Order.dao.find("SELECT * FROM `order` WHERE user_id =? AND status_id = 5",userId);
        if(userList.size() > 3){
            returnJson(0, "存在未完成支付订单");
            return;
        }

        Integer typeId = getParaToInt("typeId");
        Integer amount = getParaToInt("amount");
        String remarks = getPara("remarks");
        String mobileNumber = getPara("mobileNumber");
        Long couponCode = getParaToLong("couponCode");
        Long targetId = getParaToLong("targetId");
        Long sellerId = null;
        Float unitPrice = null;
        String currentDate = DateUtil.dateToStr(new Date());
        Float price = 0F;
        if (typeId == 23) {
            Ticket ticket = Ticket.dao.findById(targetId);
            if (ticket != null && ticket.getSurplusTotal() > 0) {
                sellerId = ticket.getSellerId();
                unitPrice = ticket.getPrice();
                price = ticket.getPrice();
            } else {
                returnJson(0, "操作失败，门票已售空");
                return;
            }
        } else if (typeId == 24) {
            Chartered chartered = Chartered.dao.findById(targetId);
            //判断改司机服务时间是否满足客户要求

            Date startDate = DateUtil.strToDate(getPara("startTime"));
            Date endDate = DateUtil.strToDate(getPara("endTime"));
            if (chartered != null && !(chartered.getDeleteTime() != null)) {
                boolean serverWeek = false;

                String startStr = DateUtil.dataToYyyyMmDd(startDate);
                String endStr = DateUtil.dataToYyyyMmDd(DateUtil.addDate(endDate));
                //筛选出时间不匹配的包车内容
                List<DriverJoinSt> list = DriverJoinSt.dao.find("SELECT * FROM driver_join_st WHERE chartered_id=?", chartered.getId());
                while (!(endStr.equals(startStr))) {
                    for (DriverJoinSt tt : list) {
                        if (tt.getServiceTimeId() == DateUtil.getWeekToInt(DateUtil.strToDate(startStr, "yyyy-MM-dd"))) {
                            serverWeek = true;
                            break;
                        } else {
                            serverWeek = false;
                        }
                    }
                    startDate = DateUtil.addDate(startDate);
                    startStr = DateUtil.dataToYyyyMmDd(startDate);
                }
                if (DateUtil.compareTime(DateUtil.dataToHhMmSs(startDate), DateUtil.dataToHhMmSs(chartered.getStartTime()))
                        && DateUtil.compareTime(DateUtil.dataToHhMmSs(chartered.getEndTime()), DateUtil.dataToHhMmSs(endDate))
                        && serverWeek) {
                    sellerId = chartered.getSellerId();
                    unitPrice = chartered.getPrice();
                    startDate = DateUtil.strToDate(getPara("startTime"));
                    List<Reserve> listReserve = Reserve.dao.find("SELECT * FROM reserve WHERE driver_id = ? AND ( (start_time < ? AND ?< end_time ) OR (start_time < ? AND ? < end_time))", sellerId, startDate, startDate, endDate, endDate);
                    if (StrKit.notNull(listReserve) && listReserve.size() > 0) {
                        returnJson(0, "操作失败，预约时间冲突");
                        return;
                    } else {
                        Reserve reserve = new Reserve();
                        reserve.setCharteredId(chartered.getId());
                        reserve.setDriverId(sellerId);
                        //reserve.setUserId(userId);
                        reserve.setStartTime(startDate);
                        reserve.setEndTime(endDate);
                        reserve.setCreateTime(new Date());
                        reserve.save();
                    }
                } else {
                    returnJson(0, "操作失败，预约时间不合法");
                    return;
                }
            } else {
                returnJson(0, "操作失败，包车内容不合法");
                return;
            }
        }

        Long statusId = 5L;//订单状态默认为5，表示未支付
        Long verifyCodeStatus = 14L; //验证码状态默认为14，表示待生成验证码，15为已验证，13为待验证
        Long couponId = null;
        Float youhui = 0F;
        //优惠券使用状态，17表示未使用
        Long couponStatusId = 17L;
        Coupon coupon = Coupon.dao.findFirst("SELECT * FROM coupon WHERE coupon_code = ? AND start_time <= ? AND end_time >= ? AND surplus_number >0 AND delete_time IS NULL", couponCode, currentDate, currentDate);
        if (coupon != null) {

            Order couponOrder = Order.dao.findFirst("SELECT * FROM `order` WHERE user_id =? AND coupon_id = ? AND status_id != 6",user.getId(), coupon.getId());
            if(couponOrder != null){
                returnJson(0, "此优惠券已使用");
                return;
            }

            couponId = coupon.getId();
            youhui = coupon.getValue();
            //优惠券使用状态，17表示未使用
            couponStatusId = 18L;
            Ticket ticket = Ticket.dao.findById(targetId);
            if (!(ticket != null && (ticket.getPrice() * amount) >= coupon.getSatisfyValue())){
                returnJson(0, "优惠券使用条件不足,请提高价格后使用。");
                return;
            }else if( coupon.getTypeId() == 32){
                returnJson(0, "此优惠券为包车订单优惠券,请重新填写。");
                return;
            }
        }else if (couponCode != null) {
            returnJson(0, "优惠券已过期或数量不足,请重新填写。");
            return;
        }

        result.put("lastPrice", price * amount - youhui);
        String orderNumber = RandomUtil.createRandomOrderNumber();
        Order verifyOrder = Order.dao.findFirst("SELECT * FROM `order` WHERE order_number = ? ", orderNumber);
        while (verifyOrder != null) {
            orderNumber = RandomUtil.createRandomOrderNumber();
            verifyOrder = Order.dao.findFirst("SELECT * FROM `order` WHERE order_number = ? ", orderNumber);
        }

        Order order = new Order();
        order.setOrderNumber(orderNumber);
        order.setSellerId(sellerId);
        order.setUserId(userId);
        order.setTypeId(typeId);
        order.setTargetId(targetId);
        order.setAmount(amount);
        order.setUnitPrice(unitPrice);
        order.setStatusId(statusId);
        order.setCouponId(couponId);
        order.setCouponStatusId(couponStatusId);
        order.setRemark(remarks);
        order.setMobileNumber(mobileNumber);
        order.setVerifyCodeStatus(verifyCodeStatus);
        order.setCreateTime(new Date());
        if (order.save()) {
            if (couponId != null) {
                coupon.setSurplusNumber(coupon.getSurplusNumber() - 1);
                coupon.setStatusId(18L);
                coupon.update();
            }
            result.put("returnCode", 1);
            int photoType = 14;//表示门票券票logo图片类型
            if (typeId == 23) {
                Ticket ticket = Ticket.dao.findById(targetId);
                if (ticket.getSurplusTotal() >= amount) {
                    ticket.setSurplusTotal(ticket.getSurplusTotal() - amount);
                } else {
                    returnJson(0, "操作失败，数量不足");
                    return;
                }
                ticket.update();
                result.put("target", ticket);
            } else if (typeId == 24) {
                Chartered chartered = Chartered.dao.findById(targetId);
                result.put("target", chartered);
                photoType = 16; //表示包车陪游logo图片类型
            }

            Photo photo = Photo.dao.findFirst("SELECT * FROM photo WHERE type_id =? AND target_id=?", photoType, targetId);
            result.put("orderNumber", orderNumber);
            result.put("targetLogo", photo != null ? photo.getPath() : Constant.XinXiLan.DEFAULT_PHOTO_PATH);


            //15分钟后检查订单是否支付，如未支付则将订单状态更改为已过期
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    Order checkOrderPayStatus = Order.dao.findById(order.getId());
                    if (checkOrderPayStatus.getPaymentTime() == null) {
                        checkOrderPayStatus.setStatusId(6L);//6 表示订单已过期
                        checkOrderPayStatus.update();
                        //订单已过期，返回优惠券库存
                        CouponHandler.cancelCoupon(checkOrderPayStatus.getId());
                        if (checkOrderPayStatus.getTypeId() == 24) {
                            Reserve reserve = Reserve.dao.findFirst("SELECT * FROM reserve WHERE user_id =? AND driver_id=? AND chartered_id=?",
                                    checkOrderPayStatus.getUserId(), checkOrderPayStatus.getSellerId(), checkOrderPayStatus.getId());
                            if (reserve != null) {
                                reserve.setDeleteTime(new Date());
                                reserve.update();
                            }
                        } else if (checkOrderPayStatus.getTypeId() == 23) {
                            Ticket ticket = Ticket.dao.findById(checkOrderPayStatus.getTargetId());
                            ticket.setSurplusTotal(ticket.getSurplusTotal() + checkOrderPayStatus.getAmount());
                            ticket.update();
                        }
                        System.out.println("--------------------------订单主键为：" + order.getId() + "--------的订单在15分钟之内未完成支付，订单已失效");
                    }
                }
            }, TimeUnit.MINUTES.toMillis(15));// 设定指定的时间time,此处为15分钟
            renderJson(result);
        } else {
            returnFailureJson();
        }
    }

}
